import argparse
import os
from typing import List, Tuple
from strutil import parse_brace_dict
from csv2sqlite import create_table_from_csv

def mem_scope_dump_data_handler(headers: List[str], rows: List[List[str]]) -> Tuple[List[str], List[List[str]]]:
    import copy
    new_rows = []
    if 'Attr' in headers:
        attr_idx = headers.index('Attr')
        for row in rows:
            if attr_idx >= len(row):
                print(f"❕ 跳过无效行：{row}")
                continue
            new_row = copy.deepcopy(row)
            new_row[attr_idx] = parse_brace_dict(row[attr_idx])
            new_rows.append(new_row)
    if 'Timestamp(ns)' in headers:
        ts_idx = headers.index('Timestamp(ns)')
        sorted(new_rows, key=lambda x: x[ts_idx])
    return headers, new_rows

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="将memscope(原名msleaks)采集输出件csv转换为sqlitedb, 以适配MindStudio Insight导入可视化。")
    parser.add_argument("--csv_file", help="输入的 CSV 文件路径")
    parser.add_argument("--db_file", default="leaks_dump_0.db", help="输出的 SQLite 数据库文件路径, 缺省为leaks_dump_0.db")
    parser.add_argument("--table", default="leaks_dump", help="表名（默认: leaks_dump）")

    args = parser.parse_args()

    if not os.path.isfile(args.csv_file):
        print(f"❌ 错误: CSV 文件 '{args.csv_file}' 不存在！")
        exit(-1)

    try:
        create_table_from_csv(
            csv_file=args.csv_file,
            db_file=args.db_file,
            table_name=args.table,
            csv_reader_post_handler=mem_scope_dump_data_handler
        )
    except Exception as e:
        print(f"❌ 转换失败: {e}")
        raise
    
    